<template>
	<view v-if="startStatus === 0">
		<view class="m-top10">
			<u-swiper :list="bannerList" keyName="slideIcon" indicator indicatorMode="line" circular></u-swiper>
			<view class="m-top10">
				<u-subsection :list="classList" keyName="classifyName" :current="current" activeColor="#1989fa"
					@change="sectionChange">
				</u-subsection>
			</view>
			<view style="padding: 20rpx;" v-if="current === 0">
				<uni-card :is-shadow="false" :border="false" is-full>
					<u-row>
						<u-col span="9">
							<u--input type="number" v-model="phoneNumber" @change="changePhoneNum" maxlength="11"
								placeholder="请输入手机号码" border="none" clearable>
							</u--input>
						</u-col>
						<u-col span="2">
							<u--text type="info" size="12" :text="operator"> </u--text>
						</u-col>
						<u-col span="1" align="center" @click="chooseContact">
							<u-icon name="man-add" size="24" customStyle="margin-left: 20rpx;"></u-icon>
						</u-col>
					</u-row>
				</uni-card>
				<block v-if="callsOperatorsList.length > 0">
					<view style="margin-top: 20rpx;" v-for="(item,index) in callsOperatorsList" :key="index">
						<uni-card :is-shadow="false" :border="false" is-full spacing="20rpx">
							<template v-slot:title>
								<u-row>
									<u-col span="7">
										<u-row>
											<u-col span="1">
												<i class="iconfont icon-mobile col-blue" style="font-size: 40upx;"></i>
											</u-col>
											<u-col span="7" offset="0.3">
												<u--text type="info" size="17" color="#222" :bold="true"
													:text="item.callsOperatorsName">
												</u--text>
											</u-col>
										</u-row>
									</u-col>
									<u-col span="5">
										<u--text prefixIcon="clock" size="14" align="right"
											iconStyle="font-size: 19px;margin-right:7rpx" text="72小时内完成"></u--text>
									</u-col>
								</u-row>
							</template>
							<view class="dis-flex align-items-center" style="flex-wrap: wrap;">
								<block v-for="(each,childrenIndex) in item.children" :key="childrenIndex">
									<view @click="toPay(item,each)"
										class="card-lists dis-flex flex-d-c align-items-center justify-around ">
										<view style="color: #1777FF;">
											{{each.callsProductsActualPrices}}
										</view>
										<view style="color: #888888;font-size: 26rpx;">
											官方价￥{{each.callsProductsStandardPrices}}
										</view>
										<view style="color: #FC2123;">
											￥{{each.callsProductsOfficialPrices}}
										</view>
									</view>
								</block>
							</view>
						</uni-card>
					</view>
				</block>
				<block v-else>
					<u-empty marginTop="20"> </u-empty>
				</block>
				<view style="margin-top: 20rpx;">
					<uni-card :is-shadow="false" :border="false" is-full spacing="20rpx">
						<template v-slot:title>
							<u-row>
								<u-col span="7">
									<u-row>
										<u-col span="1">
											<i class="iconfont icon-mobile col-blue" style="font-size: 40upx;"></i>
										</u-col>
										<u-col span="7" offset="0.3">
											<u--text type="info" size="17" color="#222" :bold="true" text="注意事项">
											</u--text>
										</u-col>
									</u-row>
								</u-col>
								<u-col span="5">
									<u--text prefixIcon="clock" size="14" align="right" @click="toRechargeRecord"
										iconStyle="font-size: 19px;margin-right:7rpx" text="充值记录"></u--text>
								</u-col>
							</u-row>
						</template>
						<view class="notice">
							<p>
								1.话费慢充日常72小时内到账，月初月末高峰期96小时内到账，超时未到账全额退款，不支持催单，急用勿下单;
							</p>
							<p>
								2.下单后，系统会自动提交充值，人工无法干预退款或更改号码，请您仔细核对充值号码，充错号码概不负责；
							</p>
							<p>
								3.副卡不支持充值，请勿提交;
							</p>
							<p>
								4.携号转网、虚拟号段、运营商黑名单等特殊号码无法充值，充值失败全额退款;
							</p>
							<p>
								5.话费慢充不支持开发票；
							</p>
							<p>
								6.维护地区：湖南电信。
							</p>
						</view>
					</uni-card>
				</view>
			</view>
			<!-- 电费充值 -->
			<view style="padding: 20rpx;" v-if="current === 1">
				<uni-card :is-shadow="false" :border="false" is-full>
					<u-row>
						<u-col span="9">
							<u--input type="number" maxlength="8" v-model="neea" placeholder="请输入户号" border="none" clearable>
							</u--input>
						</u-col>
						<u-col span="3">
							<u--text type="info" size="12" align="right" text="如何查户号？" @click="showNotice = true">
							</u--text>
						</u-col>
					</u-row>
				</uni-card>
				<block v-if="electriCityOperatorList.length > 0">
					<view style="margin-top: 20rpx;" v-for="(item,index) in electriCityOperatorList" :key="index">
						<uni-card :is-shadow="false" :border="false" is-full spacing="20rpx">
							<template v-slot:title>
								<u-row>
									<u-col span="7">
										<u-row>
											<u-col span="1">
												<i class="iconfont icon-mobile col-blue" style="font-size: 40upx;"></i>
											</u-col>
											<u-col span="7" offset="0.3">
												<u--text type="info" size="17" color="#222" :bold="true"
													:text="item.electricityOperatorsName">
												</u--text>
											</u-col>
										</u-row>
									</u-col>
									<u-col span="5">
										<u--text prefixIcon="clock" size="14" align="right"
											iconStyle="font-size: 19px;margin-right:7rpx" text="72小时内完成"></u--text>
									</u-col>
								</u-row>
							</template>
							<view class="dis-flex align-items-center" style="flex-wrap: wrap;">
								<block v-for="(each,childIndex) in item.children" :key="childIndex">
									<view @click="toPayElectricity(item,each)" class="card-lists dis-flex flex-d-c align-items-center justify-around ">
										<view style="color: #1777FF;">
											{{each.electricityProductsActualPrices}}
										</view>
										<view style="color: #888888;font-size: 32rpx;">
											官方价￥{{each.electricityProductsStandardPrices}}
										</view>
										<view style="color: #FC2123;">
											￥{{each.electricityProductsOfficialPrices}}
										</view>
									</view>
								</block>
							</view>
						</uni-card>
					</view>
				</block>
				<block v-else>
					<u-empty marginTop="20" ></u-empty>
				</block>

				<view style="margin-top: 20rpx;">
					<uni-card :is-shadow="false" :border="false" is-full spacing="20rpx">
						<template v-slot:title>
							<u-row>
								<u-col span="7">
									<u-row>
										<u-col span="1">
											<i class="iconfont icon-mobile col-blue" style="font-size: 40upx;"></i>
										</u-col>
										<u-col span="7" offset="0.3">
											<u--text type="info" size="17" color="#222" :bold="true" text="注意事项">
											</u--text>
										</u-col>
									</u-row>
								</u-col>
								<u-col span="5">
									<u--text prefixIcon="clock" size="14" align="right"
										iconStyle="font-size: 19px;margin-right:7rpx" text="充值记录"></u--text>
								</u-col>
							</u-row>
						</template>
						<view class="notice">
							<p>
								1.南网用户暂不支持欠费充值，国网用户欠费不能超出100，充值金额必须大于欠费金额;
							</p>
							<p>
								2.电费充值日常24小时内到账，高峰期72小时内到账，超时未到账全额退款，不支持催单，急用勿下单;
							</p>
							<p>
								3.下单后，系统会自动提交充值，人工无法干预退款或更改订单，请您仔细核对地区及户号，充错概不负责；
							</p>
							<p>
								4.充值成功后，可到当地电业局开具对应额度的发票；
							</p>
							<p>
								5.充值可能会有分批到账的情况，可在“网上国网APP（国家电网）”、“南网在线APP(南方电网）”、“支付宝或微信的生活缴费专区”查询电费余额，如48小时还未到账且未退款，请及时联系客服;
							</p>
							<p>
								6.持电卡非智能电表用户不支持该缴费业务。
							</p>
						</view>
					</uni-card>
				</view>
			</view>
		</view>
		<u-popup :show="showPayPopup" @close="showPayPopup = false" @open="showPayPopup = true" round="10" closeable>
			<view style="height: 800rpx;">
				<u--text color="#1989fa" :text="'￥'+orderInfo.callsProductsActualPrices" :bold="true" size="40"
					align="center" lineHeight="150"></u--text>
				<u--text color="#222" :text="callsOperatorsName+orderInfo.callsProductsOfficialPrices+'元'" :bold="true"
					align="center" lineHeight="40">
				</u--text>
				<u--text color="#222" text="到账时间:1-72小时（高峰期96小时内）" :bold="true" align="center" lineHeight="40">
				</u--text>
				<view style="display: flex;">
					<view style="margin-left: 200rpx;">
						<u--text :block="true" text="充值号码: " :bold="true" align="right" lineHeight="40"></u--text>
					</view>
					<u--text :block="true" color="#fa3534" :text="phoneNumber" :bold="true" align="left"
						lineHeight="40">
					</u--text>
				</view>
				<u--text color="#fa3534" text="请仔细核对号码,输错号码后果自负" :bold="true" align="center" lineHeight="40"></u--text>
				<u-row>
					<u-col span="6">
						<u--text text="充值前请阅读" :bold="true" align="right" lineHeight="40"></u--text>
					</u-col>
					<u-col span="6">
						<u--text color="#1989fa" @click="showRule = true" text="《充值须知》" lineHeight="40"></u--text>
					</u-col>
				</u-row>
				<u-button @click="payment" type="primary" customStyle="width:400rpx;" text="立即充值"></u-button>
			</view>
		</u-popup>
		<u-popup :show="showPayElectricityPopup" @close="showPayElectricityPopup = false" @open="showPayElectricityPopup = true" round="10" closeable>
			<view style="height: 800rpx;">
				<u--text color="#1989fa" :text="'￥'+orderInfo.electricityProductsActualPrices" :bold="true" size="40"
					align="center" lineHeight="150"></u--text>
				<u--text color="#222" :text="callsElectricityName+orderInfo.electricityProductsActualPrices+'元'" :bold="true"
					align="center" lineHeight="40">
				</u--text>
				<u--text color="#222" text="到账时间:1-72小时（高峰期96小时内）" :bold="true" align="center" lineHeight="40">
				</u--text>
				<view style="display: flex;">
					<view style="margin-left: 200rpx;">
						<u--text :block="true" text="充值户号: " :bold="true" align="right" lineHeight="40"></u--text>
					</view>
					<u--text :block="true" color="#fa3534" :text="neea" :bold="true" align="left"
						lineHeight="40">
					</u--text>
				</view>
				<u--text color="#fa3534" text="请仔细核对号码,输错号码后果自负" :bold="true" align="center" lineHeight="40"></u--text>
				<u-row>
					<u-col span="6">
						<u--text text="充值前请阅读" :bold="true" align="right" lineHeight="40"></u--text>
					</u-col>
					<u-col span="6">
						<u--text color="#1989fa" @click="showElectricityRule = true" text="《充值须知》" lineHeight="40"></u--text>
					</u-col>
				</u-row>
				<u-button @click="paymentElectricity" type="primary" customStyle="width:400rpx;" text="立即充值"></u-button>
			</view>
		</u-popup>
		<u-modal :show="showRule" :title="title" @confirm="showRule = false">
			<view class="slot-content">
				<rich-text :nodes="content"></rich-text>
			</view>
		</u-modal>
		<u-modal :show="showElectricityRule" :title="title" @confirm="showElectricityRule = false">
			<view class="slot-content">
				<rich-text :nodes="electricityContent"></rich-text>
			</view>
		</u-modal>
		<u-popup :show="showNotice" @close="showNotice = false" @open="showNotice = true" round="10" closeable>
			<view style="height: 700rpx;" class="padding20">
				<u--text :text="popupTitle" :bold="true" align="center"></u--text>
				<u--text text="【电话查询】" :bold="true" lineHeight="40"></u--text>
				<u--text text="拨打电网客服电话(95598),提供客户名称表号、联系电话、身份证中的两项及以上信息即可查询。"></u--text>
				<u--text text="【查找短信】" :bold="true" lineHeight="40"></u--text>
				<u--text text="搜索手机内95598的相关短信,短信中可能包含户号。"></u--text>
				<u--text text="【其他方式】" :bold="true" lineHeight="40"></u--text>
				<u--text text="在电力提供的电费发票或银行等代售电网点提供的收据查询。"></u--text>
			</view>
		</u-popup>
		<Tabbar :current="1" v-if="startStatus === 0"></Tabbar>
	</view>
</template>

<script>
	import {
		check
	} from '@/utils/phoneNumberUtils.js'
	import {
		getClassiyfs,
		getSlides,
		getCallsOperators,
		getCallsOperatorsId,
		getOpenId,
		getWxUserinfo,
		toPayApi,
		getDisposeOrder,
		getElectriCityOperators,
		getElectriCityOperatorsId,
		toPayPlusApi
	} from '@/api/index.js'
	export default {
		components: {

		},
		data() {
			return {
				startStatus:uni.getStorageSync('startStatus'),
				bannerList: [],
				classList: [],
				list: ['话费充值', '电费充值'],
				current: 0,
				cardList: ['1', '2', '3'],
				showPayPopup: false,
				showPayElectricityPopup:false,
				callsOperatorsList: [],
				electriCityOperatorList:[],
				phoneNumber: '',
				neea:'',
				operator: '',
				callsOperatorsName: '',
				callsElectricityName:'',
				orderInfo: {},
				showRule: false,
				showElectricityRule:false,
				title: '充值须知',
				content: `1.话费慢充日常72小时内到账，月初月末高峰期96小时内到账，超时未到账全额退款，不支持催单，急用勿下单；<br>
				2.下单后，系统会自动提交充值，人工无法干预退款或更改号码，请您仔细核对充值号码，充错号码概不负责；<br>
				3.副卡不支持充值，请勿提交；<br>
				4.携号转网、虚拟号段、运营商黑名单等特殊号码无法充值，充值失败全额退款；<br>
				5.话费慢充不支持开发票;`,
				electricityContent: `1.南网用户暂不支持欠费充值，国网用户欠费不能超出100，充值金额必须大于欠费金额；<br>
				2.电费充值日常24小时内到账，高峰期72小时内到账，超时未到账全额退款，不支持催单，急用勿下单；<br>
				3.下单后，系统会自动提交充值，人工无法干预退款或更改订单，请您仔细核对地区及户号，充错概不负责；<br>
				4.充值成功后，可到当地电业局开具对应额度的发票；<br>
				5.充值可能会有分批到账的情况，可在“网上国网APP（国家电网）”、“南网在线APP（南方电网）”、“支付宝或微信的生活缴费专区”查询电费余额，如72小时还未到账且未退款，请及时联系客服；<br>
				6.持电卡非智能电表用户不支持该缴费业务。`,
				showNotice: false,
				popupTitle: '如何查找户号？',
				region: '选择地区',
				showPhoneNumberList: false,
				columns: [
					[
						'暂无历史记录'
					]
				],
				historyPhonelist: [],

			}
		},
		onLoad(e) {
			console.log(e);
			this.getBannerList();
			this.classiyfs();
			this.getCallsOperatorList(1)


		},
		onShow(e) {
			let type = uni.getStorageSync('type')
			console.log('缓存中的type,', type);
			type === 2 ? this.current = 1 : this.current = 0
			if (type === 2) {
				this.getElectriCityOperatorList(type)
			}
			uni.removeStorageSync('type')
		},
		methods: {
			// 轮播
			async getBannerList() {
				const {
					data: res
				} = await getSlides()
				this.bannerList = res.data
			},
			async classiyfs() {
				const {
					data: res
				} = await getClassiyfs()
				let classList = res.data;
				classList = classList.slice(0, 2)
				this.classList = classList;
			},
			// 话费产品分类
			async getCallsOperatorList(classifyId) {
				const {
					data: res
				} = await getCallsOperators(classifyId)
				let callsOperatorsId = res.data
				console.log('callsOperatorsId', res.data);
				for (let i = 0; i < callsOperatorsId.length; i++) {
					const result = await this.getCallsOperatorsIdItem(callsOperatorsId[i].callsOperatorsId)
					callsOperatorsId[i].children = result
					console.log(callsOperatorsId[i]);
				}
				console.log('data中的', callsOperatorsId);
				this.callsOperatorsList = callsOperatorsId;
			},
			//话费下列表数据
			async getCallsOperatorsIdItem(callsOperatorsId) {
				const {
					data: res
				} = await getCallsOperatorsId(callsOperatorsId)
				if (res.data.length > 0) {
					return res.data
				}
			},
			
			// 电费列表
			async getElectriCityOperatorList(classifyId) {
				let that = this;
				const {
					data: res
				} = await getElectriCityOperators(classifyId)
				console.log(res.data);
				for (let i = 0;i<res.data.length;i++) {
					console.log(res.data[i].electricityOperatorsId);
					const {data:result} = await getElectriCityOperatorsId(res.data[i].electricityOperatorsId)
					console.log(result.data);
					res.data[i].children = result.data
				}
				console.log(res.data);
				this.electriCityOperatorList = res.data;
			},

			sectionChange(index) {
				if (index === this.current) {
					return
				}
				this.current = index;
				let classifyId = index === 0 ? classifyId = 1 : classifyId = 2
				index === 0 ? this.getCallsOperatorList(classifyId) : this.getElectriCityOperatorList(classifyId);
			},
			changePhoneNum(e) {
				if (e.length === 11) {
					this.operator = check(e);
				}
			},

			// 选择联系人
			chooseContact() {
				let that = this;
				// #ifdef MP-WEIXIN
				wx.chooseContact({
					success: res => {
						console.log(res.phoneNumber);
						this.phoneNumber = res.phoneNumber
						console.log(check(res.phoneNumber));
						that.operator = check(res.phoneNumber);
					},
					fail: error => {
						console.log(error);
					},
				});
				// #endif
			},
			
			async isLogin() {
				let token = uni.getStorageSync('token');
				if (token = '' || !token) {
					let pages = getCurrentPages();
					const resp = await this.$publicJs.App.getUserInfo(pages);
					const code = await this.$publicJs.App.getWxCode();
					const {
						data: res
					} = await getOpenId(code);
					console.log(res);
					const openId = res.data.openid;
					let params = {
						nickName: resp.nickName,
						avatarUrl: resp.avatarUrl,
						openId
					}
					const {
						data: e
					} = await getWxUserinfo(params);
					let token = e.data;
					uni.setStorageSync('token', token);
					uni.setStorageSync('openId', openId);
					return false
				}
			},

			async toPay(item, each) {
				await this.isLogin();
				this.orderInfo = each;
				this.callsOperatorsName = item.callsOperatorsName
				let testMobile = uni.$u.test.mobile(this.phoneNumber)
				if (testMobile === false) {
					uni.showToast({ //提示信息
						title: '请输入正确的手机号',
						icon: 'none',
						duration: 1000
					});
					return
				}
				this.showPayPopup = true;
			},
			
			async toPayElectricity(item, each) {
				await this.isLogin();
				let neea = uni.$u.trim(this.neea);
				console.log(neea.length);
				if (neea.length != 8) {
					uni.showToast({ //提示信息
						title: '请输入正确的户号',
						icon: 'none',
						duration: 1000
					});
					return
				}
				this.orderInfo = each;
				console.log(each);
				this.callsElectricityName = item.electricityOperatorsName
				this.showPayElectricityPopup = true;
			},
			
			changeRegion(e) {
				console.log(e.data[1]);
				this.region = e.data[1];
			},
			confirmPhone(e) {
				console.log(e.value);
				this.showPhoneNumberList = false
			},

			// 支付
			payment() {
				this.getCodeOpenId();
			},
			// 获取openid
			async getCodeOpenId() {
				let that = this;
				const code = await this.$publicJs.App.getWxCode()
				const {
					data: res
				} = await getOpenId(code);
				const {
					openid
				} = res.data;
				let Callsdto = {
					openid,
					phoneNumber: this.phoneNumber,
					callsOperatorsId: this.orderInfo.callsOperatorsId,
					callsProductsId: this.orderInfo.callsProductsId,
					callsProductsActualPrices: this.orderInfo.callsProductsActualPrices
				}
				const {
					data: resp
				} = await toPayApi(Callsdto);
				console.log(resp);
				uni.requestPayment({
					timeStamp: resp.data.timeStamp, // 时间戳，必填（后台传回）
					nonceStr: resp.data.nonceStr, // 随机字符串，必填（后台传回）
					package: resp.data.repay_id, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
					signType: resp.data.signType, // 签名算法，非必填，（预先约定或者后台传回）
					paySign: resp.data.paySign, // 签名 ，必填 （后台传回）
					success: function(e) {
						// 成功后的回调函数
						console.log(e);
						uni.showToast({
							title: '支付成功'
						})
						that.showPayPopup = false;
						that.phoneNumber = false;
						that.sendDisposeOrder(
							resp.data.repay_id,
							"200"
						);
					},
					fail(err) {
						console.log(err);
						uni.showToast({
							title: '支付失败',
							icon: 'error'
						})
						that.sendDisposeOrder(
							resp.data.repay_id,
							"500"
						);
					}
				});
			},
			
			// 电费支付
			async paymentElectricity() {
				let that = this;
				const code = await this.$publicJs.App.getWxCode()
				const {
					data: res
				} = await getOpenId(code);
				const {
					openid
				} = res.data;
				let Electricitydto = {
					openid,
					electricityNumber: this.neea,
					electricityOperatorsId: this.orderInfo.electricityOperatorsId,
					electricityProductsId: this.orderInfo.electricityProductsId,
					electricityProductsActualPrices: this.orderInfo.electricityProductsActualPrices
				}
				console.log('电费支付参数',Electricitydto);
				const {
					data: resp
				} = await toPayPlusApi(Electricitydto);
				console.log(resp);
				uni.requestPayment({
					timeStamp: resp.data.timeStamp, // 时间戳，必填（后台传回）
					nonceStr: resp.data.nonceStr, // 随机字符串，必填（后台传回）
					package: resp.data.repay_id, // 统一下单接口返回的 prepay_id 参数值，必填（后台传回）
					signType: resp.data.signType, // 签名算法，非必填，（预先约定或者后台传回）
					paySign: resp.data.paySign, // 签名 ，必填 （后台传回）
					success: function(e) {
						// 成功后的回调函数
						console.log(e);
						uni.showToast({
							title: '支付成功'
						})
						that.showPayElectricityPopup = false;
						that.neea = '';
						that.sendDisposeOrder(
							resp.data.repay_id,
							"200"
						);
					},
					fail(err) {
						console.log(err);
						uni.showToast({
							title: '支付失败',
							icon: 'error'
						})
						that.sendDisposeOrder(
							resp.data.repay_id,
							"500"
						);
					}
				});
			},

			// 支付回调
			async sendDisposeOrder(repay_id, code) {
				console.log(repay_id, code);
				var StringNumber = String(repay_id);
				const orderTradeNumber = StringNumber.substring(10, repay_id.length)
				console.log(orderTradeNumber)
				const {
					data: res
				} = await getDisposeOrder(orderTradeNumber, code);
				console.log(res);
			},

			toRechargeRecord() {
				uni.switchTab({
					url: '/pages/order/index?a=' + 1
				})
			},
		}
	}
</script>

<style lang="scss">
	.card-lists {
		width: 30%;
		height: 240rpx;
		background: #E9F0FF;
		border-radius: 20rpx;
		font-weight: bold;
		font-size: 40rpx;
		padding: 20rpx 0;
		margin: 0 20rpx 20rpx 0;
		box-sizing: border-box;
	}

	.notice {
		background: #E9F0FF;
		padding: 20rpx;

		p {
			color: #1777FF;
			font-weight: bold;
			font-size: 30rpx;
		}
	}
</style>
